package cn.edu.gzu.interceptor;

import cn.edu.gzu.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, User> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        System.out.println("token：" + token);

        if (token != null && !token.isEmpty()) {
            // 去掉Bearer，只留下Token的值
            String authToken = token.substring(7);

            // 如果请求头中带有 token，就进行 token 验证
            try {
                return true;
            } catch (Exception e) {
                // 如果验证失败，就跳转到登录界面
                System.out.println("token无效我跳转");
                response.sendRedirect(request.getContextPath() + "/pages/login.html");
                return false;
            }
        } else {

            // 否则跳转到登录界面
            System.out.println("没有token我跳转");
            response.sendRedirect(request.getContextPath() + "/pages/login.html");
            return false;
        }

    }
}